package cn.wolfcode.wolf2w.interceptor;

import cn.wolfcode.wolf2w.annotation.RequireLogin;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.service.IUserinfoRedisService;
import cn.wolfcode.wolf2w.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class CheckLoginInterceptor implements HandlerInterceptor {

    @Autowired
    private IUserinfoRedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        String token = request.getHeader("token");
        UserInfo user = redisService.getToken(token);

        HandlerMethod handlerMethod = (HandlerMethod) handler;

        //2:如果有进行登录校验
        if (handlerMethod.hasMethodAnnotation(RequireLogin.class)) {
            if (user == null) {
                //没有登录
                response.setContentType("application/json; charset=utf-8"); //json数据中文转码
                response.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));
                return false;
            }
        }
        //3:如果没有放行
        return true;
    }
}